package com.whsr.readservice.controller;

import com.whsr.readservice.service.FileUploadService;
import com.whsr.readservice.vo.AttachMent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/server/file/")
public class FileUploadController {

    @Autowired
    private final FileUploadService fileUploadService;
    private HashMap<String, Object> resultMap = new HashMap<>();

    public FileUploadController(FileUploadService fileUploadService) {
        this.fileUploadService = fileUploadService;
    }

    @RequestMapping("imgUpload")
    @ResponseBody
    public Object imgUpload(@RequestBody Map<String, Object> parMap){
        resultMap = new HashMap<>();
        try{
            AttachMent attachMent = new AttachMent();
            String imgstr = parMap.get("img").toString();
            BASE64Decoder decoder = new BASE64Decoder();
            attachMent.setContent(decoder.decodeBuffer(imgstr.replace("data:image/jpeg;base64,", "").replace("data:image/png;base64,", "")));
//            attachMent.setContent(imgstr.substring((imgstr.indexOf("base64,") + 7), imgstr.length()).getBytes("utf-8"));
//            attachMent.setContent(imgstr.replace("data:image/jpeg;base64,", "").getBytes());
            attachMent.setIsUse(0);
            attachMent.setCreateTime(new Date());
            this.fileUploadService.imgUpload(attachMent);
            resultMap.put("errno", 0);
            resultMap.put("msg", "image upload success");
            resultMap.put("data", attachMent);
        }catch (Exception e){
            resultMap.put("errno", -1);
            resultMap.put("msg", "image upload filed");
        }
        return resultMap;
    }


    @RequestMapping(value = "imgView/{id}", method = RequestMethod.GET)
    public void imgView(@PathVariable int id, HttpServletResponse res){
        AttachMent attachMent = this.fileUploadService.getImgById(id);
        String fileName = id + "_" + new Date().getTime() + ".png";
        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = attachMent.getContent();
        OutputStream os = null;
        try {
            os = res.getOutputStream();
            os.write(buff);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("success");
    }

}
